﻿/*
 * 由SharpDevelop创建。
 * 用户： Hastone
 * 日期: 2014/3/19
 * 时间: 16:50
 * 
 * 要改变这种模板请点击 工具|选项|代码编写|编辑标准头文件
 */
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.IO;

namespace ProgramerInput
{
    /// <summary>
    /// Description of MainForm.
    /// </summary>
    public partial class MainForm : Form
    {
        private const string nl = "\r\n";
        private string pname = "";

        private Dictionary<string, string> config;
        private string sh = "0";

        public MainForm()
        {
            //
            // The InitializeComponent() call is required for Windows Forms designer support.
            //
            InitializeComponent();

            //
            // TODO: Add constructor code after the InitializeComponent() call.
            //
            this.FormClosing += (se, ev) =>
            {
                keyLogs.stopLoging();
                keyLogs = null;
                //MessageBox.Show("end");
            };

            Program.path = System.AppDomain.CurrentDomain.BaseDirectory;
            Program.path = Program.path.Trim('\\');

            pname = System.Windows.Forms.Application.ExecutablePath;
            pname = pname.Replace(Program.path + "\\", "");
            pname = pname.Substring(0, pname.Length - 4);

            st += "当前程序名" + pname + nl;

            loadConfig();

            st += "Esc+F1 隐藏程序" + nl;
            st += "Esc+F2 显示程序" + nl;
            st += "Esc+F3 重载配置" + nl;
            st += "Esc+F4 关闭程序" + nl;
            
            if (config.ContainsKey("hidestart") && config["hidestart"] == "1")
            {
                sh = "1";
            }

            StartLog();

            Program.isStartComplate = true;
        }


        KeybordLogger keyLogs = null;
        //		string logPath = System.Environment.CurrentDirectory.ToString() + "\\" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".txt";
        public string st = "";
        private string _se = "";

        public string se
        {
            set
            {
                var seArr = new List<string>(_se.Split(new string[]{nl},StringSplitOptions.RemoveEmptyEntries));
                seArr.Add(value);
                while(seArr.Count>=5)
                {
                    seArr.RemoveAt(0);
                }
                _se = string.Join(nl, seArr);
            }
            get
            {
                return _se;
            }
        }

        private Timer timerChecker = new Timer();

        private void loadConfig()
        {
            if (System.IO.File.Exists(Program.path + "\\" + pname + ".ini"))
            {
                var configStr =
                    System.IO.File.ReadAllText(Program.path + "\\" + pname + ".ini");

                config = CommonHelper.ToObject<Dictionary<string, string>>(configStr);
                se = "设置已经载入" + nl;

            }
            else
            {
                config = new Dictionary<string, string>();
                config.Add("hidestart", "0");
                config.Add("Oem2 Oem2 Oem2", "send ^ <sp>wait 5000<sp>send ^ ");
                config.Add("P Y Y", "send {BACKSPACE 3}<sp>send ^ <sp>wait 10000<sp>send ^ ");

                var configStr = CommonHelper.ToString(config);
                System.IO.File.WriteAllText(Program.path + "\\" + pname + ".ini", configStr);
                //pname=
                se = "设置已经创建" + nl;
            }
        }

        private void StartLog()
        {
            CommonHelper.ThreadSleep(2000);


            if (keyLogs == null)
            {
                keyLogs = new KeybordLogger("");
                keyLogs.startLoging();



                timerChecker.Interval = 500;
                timerChecker.Tick += (s, e) =>
                {
                    tlog.Clear();
                    tlog.AppendText(DateTime.Now + nl);
                    tlog.AppendText(st + nl);
                    tlog.AppendText(keyLogs.key1 + nl);
                    tlog.AppendText(keyLogs.key2 + nl);
                    tlog.AppendText(keyLogs.key3 + nl);
                    tlog.AppendText(keyLogs.key4 + nl);
                    tlog.AppendText(keyLogs.key5 + nl);
                    tlog.AppendText(se + nl);

                    if (sh == "1")
                    {
                        Visible = false;
                        sh = "0";
                        return;
                    }

                    if (keyLogs.key2.StartsWith("Escape F"))
                    {
                        if (keyLogs.key2 == "Escape F4")
                        {
                            Close();
                            return;
                        }
                        if (keyLogs.key2 == "Escape F3")
                        {
                            keyLogs.key2 = "reload_config";
                            loadConfig();
                            return;
                        }
                        if (keyLogs.key2 == "Escape F2")
                        {
                            keyLogs.key2 = "display";
                            Visible = true;
                            return;
                        }
                        if (keyLogs.key2 == "Escape F1")
                        {
                            keyLogs.key2 = "hide";
                            Visible = false;
                            return;
                        }
                    }

                    foreach (var c in config)
                    {
                        if (c.Key == keyLogs.key1)
                        {
                            keyLogs.key1 = "execute(" + c.Key.Replace(" ", "|") + ")";
                            se = "execute(" + c.Key.Replace(" ", "|") + ")" + nl;
                            ExecuteKeySet(c.Value);
                            return;
                        }
                        if (c.Key == keyLogs.key2)
                        {
                            keyLogs.key2 = "execute(" + c.Key.Replace(" ", "|") + ")";
                            se = "execute(" + c.Key.Replace(" ", "|") + ")" + nl;
                            ExecuteKeySet(c.Value);
                            return;
                        }
                        if (c.Key == keyLogs.key3)
                        {
                            keyLogs.key3 = "execute(" + c.Key.Replace(" ", "|") + ")";
                            se = "execute(" + c.Key.Replace(" ", "|") + ")" + nl;
                            ExecuteKeySet(c.Value);
                            return;
                        }
                        if (c.Key == keyLogs.key4)
                        {
                            keyLogs.key4 = "execute(" + c.Key.Replace(" ", "|") + ")";
                            se = "execute(" + c.Key.Replace(" ", "|") + ")" + nl;
                            ExecuteKeySet(c.Value);
                            return;
                        }
                        if (c.Key == keyLogs.key5)
                        {
                            keyLogs.key5 = "execute(" + c.Key.Replace(" ", "|") + ")";
                            se = "execute(" + c.Key.Replace(" ", "|") + ")" + nl;
                            ExecuteKeySet(c.Value);
                            return;
                        }
                    }

                    //					switch(keyLogs.key3)
                    //					{
                    //						case "Oem2 Oem2 Oem2":
                    //							SendKeys.SendWait("^ ");
                    //							keyLogs.key3="ctrl+space";
                    //							break;
                    //						default:
                    //							break;
                    //					}
                };
                timerChecker.Start();

            }
            //if (keyLogs.HasStart)
            //{
            //    MessageBox.Show("Logger is working!");
            //}

        }

        private void ExecuteKeySet(string s)
        {
            string[] arr = s.Split(new string[] { "<sp>" }, StringSplitOptions.RemoveEmptyEntries);
            for (int i = 0; i < arr.Length; i++)
            {
                if (arr[i].StartsWith("check "))
                {
                    string ws = "";
                    if (CommonHelper.CheckWin(arr[i].Substring(6),out ws))
                    {
                        tlog.AppendText("check:" + ws + " pass\r\n");
                        continue;
                    }
                    else
                    {
                        tlog.AppendText("check:" + ws + " false\r\n");
                        break;
                    }
                }
                if (arr[i].StartsWith("wait "))
                {
                    CommonHelper.ThreadSleep(int.Parse(arr[i].Substring(5)));
                    continue;
                }
                if (arr[i].StartsWith("send "))
                {
                    CommonHelper.ExecuteKey(arr[i].Substring(5));
                    continue;
                }
                if (arr[i].StartsWith("load "))
                {
                    CommonHelper.ExecuteLoad(arr[i].Substring(5));
                    continue;
                }
                if (arr[i].StartsWith("text "))
                {
                    CommonHelper.ExecuteText(arr[i].Substring(5));
                    continue;
                }
                if (arr[i].StartsWith("runs "))
                {
                    CommonHelper.ExecuteRuns(arr[i].Substring(5));
                    continue;
                }
            }

        }


    }
}
